<template>
	<view>
		<u-sticky>
			<view class="home_header pb6">
				<u-navbar leftText="返回" :title="'同城趣-发现' + CityName.replace('市', '')" :safeAreaInsetTop="true"
					:fixed="false" bgColor="#fff">
					<view class="dflex f14" slot="left" @click="get_Location">
						<u-icon name="map" color="#000"></u-icon>
						<text class="ml5">{{ CityName }}</text>
					</view>
				</u-navbar>
			</view>
		</u-sticky>

			<u-sticky :customNavHeight="customNavHeight">
				<view class="dflex jcsb boxbb">
					<view class="home_tab wrap_ntb" :style="'max-width: ' + tabWidth + 'px; overflow: hidden; '">
						<u-tabs :current="current_tab" :list="home_tab_list"
							:activeStyle="{fontWeight: 'bold', transform: 'scale(1.05)'}"
							:inactiveStyle="{fontSize: '14px'}" lineWidth="25" lineHeight="5" lineColor="#FFD84A"
							@click="click" height="44px">
						</u-tabs>
					</view>
				</view>

				<view class="lbs_chioce dflex f14 aic bg_fff" v-if="show_lbs">
					<u-icon name="list" color="#000"></u-icon>
					<text class="mr5">排序</text>
					<view class="lbs_text dflex">
						<text :class="{ selected: selectedElement === item.key }" v-for="(item, index) in lbs_text"
							@click="selectElement(item.key)" :key="index">
							{{ item.name }}
						</text>
					</view>
				</view>
			</u-sticky>

		<view class="dflex p_fix bg_fff" @click="gotoSearch"
			:style="'top: ' + (customNavHeight + 10) + 'px; right: 0; display:flex; z-index:999; padding: 0 6px; border-left: 1px solid #ddd;'">
			<u-icon name="search" size="25"></u-icon>
		</view>

		<view class="empty_list" v-if="empty">
			<u-empty mode="news" icon="news"></u-empty>
		</view>

		<view v-else>
			<view class="waterfall-box h-flex-x h-flex-2">
				<view>
					<helang-waterfall v-for="(item,index) in leftList" :key="index" :params="item" tag="left"
						:index="index" @height="onHeight" @click="onClick"></helang-waterfall>
				</view>
				<view>
					<helang-waterfall v-for="(item,index) in rightList" :key="index" :params="item" @height="onHeight"
						@click="onClick" tag="right" :index="index"></helang-waterfall>
				</view>
			</view>
			<view class="load-txt">{{ajax.loadTxt}}</view>
		</view>

		<view class="bottom_menu">
			<bottomMenu></bottomMenu>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				home_tab_list: [],
				CityName: '',
				all_categories: [{
						id: 'new',
						name: '最新'
					},
					{
						id: 'recommend',
						name: '推荐'
					},
					{
						id: 'group',
						name: '团购',
						badge: {
							value: '超值'
						}
					},
				],
				lbs_text: [{
						name: '默认',
						key: 'group'
					},
					{
						name: '距离排序',
						key: 'lbs'
					}
				],
				current_tab: '',
				// 瀑布流
				leftHeight: 0,
				rightHeight: 0,
				leftList: [],
				rightList: [],
				ajax: {
					// 是否可以加载
					load: true,
					// 加载中提示文字
					loadTxt: '',
					// 每页的请求条件
					rows: 10,
					// 页码
					page: '',
				},
				// end 瀑布流
				customNavHeight: '',
				empty: false,
				//默认加载推荐内容
				current_category_id: 'recommend',
				indexList: [],
				total_page: '',
				domain: '',
				show_lbs: false,
				selectedElement: 'group',
				latitude: '',
				longitude: '',
				tabWidth: ''
			}
		},
		onShow() {
			this.getDomain()
			this.getCityName()
		},
		onLoad() {
			//获取设备信息
			var sys = uni.getSystemInfoSync()
			this.customNavHeight = sys.statusBarHeight + 50
			this.tabWidth = sys.screenWidth
			// console.log('screenWidth', sys.screenWidth)
			// this.getLocationAuth()
		},
		// 触底触发
		onReachBottom() {
			// console.log('aaaa',this.ajax.page)
			// console.log('cccc',this.total_page)
			// console.log('dddd',this.ajax.page <= this.total_page)
			if (this.ajax.page <= this.total_page) {
				this.loadIndexNew();
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			// 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
			setTimeout(() => {
				let [left, right] = [
					[],
					[]
				];
				this.leftList = left;
				this.rightList = right;
				this.ajax.page = 0;
				this.loadIndexNew();
			}, 800);
		},
		methods: {
			getDomain() {
				uni.getStorage({
					key: 'Domain',
					success: (res) => {
						this.domain = res.data
						uni.setStorageSync('domain', res.data)
						// console.log('domaindomaindomaindomain', this.domain)
						this.online_check()
					},
					fail() {
						uni.navigateTo({
							url: '/packageShop/location/location'
						})
					}
				})
			},
			gotoSearch() {
				uni.redirectTo({
					url: "/pages/search/search"
				});
			},
			selectElement(key) {
				uni.showLoading({
					title: '加载中...',
					mask: false
				});
				this.selectedElement = key;

				//清空瀑布流
				let [left, right] = [
					[],
					[]
				];
				this.leftList = left;
				this.rightList = right;
				//重置左右高度，才不会出现只有一条数据的时候忽左忽右
				this.leftHeight = 0
				this.rightHeight = 0
				uni.request({
					url: uni.getStorageSync('domain') + '/api/v1/topics?page=1&category=' + key,
					method: 'GET',
					data: {
						'latitude': this.latitude,
						'longitude': this.longitude
					},
					success: res => {
						// console.log('click.res.data',res.data);
						this.addList(res.data)
						this.ajax.page = res.data.meta.current_page
						// console.log('click.this.ajax.page',res.data.meta.current_page,this.ajax.page);
						if (res.data.data.length == 0) {
							this.empty = true
						} else {
							this.empty = false
						}
						uni.hideLoading();
					},
					fail: () => {},
					complete: () => {}
				});
			},
			get_Location() {
				uni.navigateTo({
					url: '/packageShop/location/location'
				})
			},
			//获得城市缓存
			getCityName() {
				uni.getStorage({
					key: 'City_Name',
					success: (res) => {
						this.CityName = res.data
						uni.setStorageSync('cityName', res.data)
					}
				})
			},
			//获取定位
			getLocationAuth() {
				let that = this;
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						let key =
						'4MBBZ-Y5NKR-7SLWB-WW7XD-U66TE-YEBRD'; //申请地址：https://lbs.qq.com/dev/console/application/mine
						uni.request({
							url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + that.latitude +
								',' + that.longitude + '&key=' + key,
							method: "GET",
							success(ress) {
								let data = ress.data; //获取到所有定位的数据
								let CityName = ress.data.result.address_component.city;
								uni.setStorage({
									key: 'City_Name',
									data: CityName
								})
							},
							fail() {
								// uni.showToast({
								// 	'title':'对不起，数据获取失败！',
								// 	'icon':'none'
								// })
							}
						})
					},
					fail(res) {
						uni.showToast({
							'title': '对不起，获取位置失败！',
							'icon': 'none'
						})
					}
				})
			},
			// openMeituan() {
			// 	this.$refs.meituan.getMeituan()
			// },		
			online_check() {
				uni.request({
					url: this.domain + '/api/v1/system/online/check',
					method: 'get',
					header: {
						'Accept': 'application/json',
					},
					success: (res) => {
						this.onlineCheck = res.data.status
						this.loadCategory()
						this.loadIndexNew()
						uni.hideLoading();
					},
					fail: (res) => {}
				})
			},
			loadCategory() {
				uni.showLoading({
					title: "加载中...."
				})
				uni.request({
					url: this.domain + '/api/v1/category',
					method: 'GET',
					data: {},
					success: res => {
						this.home_tab_list = res.data;
						// console.log('this.onlineCheck', this.onlineCheck)
						// 判断是否审核，审核的时候默认加载‘推荐’选项，所以是0，其他不加载
						// 不审核的时候，最新是第一个，所以默认加载是1
						if (this.onlineCheck == 1) {
							this.home_tab_list = [...this.all_categories, ...this.home_tab_list]
							this.current_tab = 1
						} else {
							this.home_tab_list.unshift(this.all_categories[1]);
							this.current_tab = 0
						}
						// this.news = res.data;
						uni.hideLoading();
					},
					fail: () => {},
					complete: () => {}
				});

			},
			loadIndexNew() {
				// uni.showLoading({
				// 	title:"加载中...."
				// })
				uni.request({
					url: this.domain + '/api/v1/topics?page=' + (this.ajax.page + 1) + '&category=' + this
						.current_category_id,
					// url: 'https://unidemo.dcloud.net.cn/api/news',
					method: 'GET',
					header: {
						'Accept': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					data: {},
					success: res => {
						// console.log('loadIndexNew', res.data);						
						if (res.data.meta.total == 0) {
							this.total_page = 0
							this.ajax.loadTxt = '';
							this.empty = true
						} else {
							this.total_page = res.data.meta.last_page
							this.empty = false
							this.addList(res.data)
							// console.log(res.data);
							this.ajax.page = res.data.meta.current_page
						}

					},
					fail: () => {},
					complete: () => {}
				});
			},
			click(e) {
				// console.log('top_menu', e.id);
				if (e.id == 'group') {
					this.show_lbs = true
				} else {
					this.show_lbs = false
				}
				this.current_category_id = e.id,
					uni.showLoading({
						title: '加载中...',
						mask: false
					});
				//清空瀑布流
				let [left, right] = [
					[],
					[]
				];
				this.leftList = left;
				this.rightList = right;
				//重置左右高度，才不会出现只有一条数据的时候忽左忽右
				this.leftHeight = 0
				this.rightHeight = 0
				// console.log('res', res.id);			
				uni.request({
					url: this.domain + '/api/v1/topics?page=1&category=' + e.id,
					method: 'GET',
					header: {
						'Accept': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					data: {},
					success: res => {
						// console.log('click.res.data',res.data);
						this.addList(res.data)
						this.ajax.page = res.data.meta.current_page
						// console.log('click.this.ajax.page',res.data.meta.current_page,this.ajax.page);
						if (res.data.data.length == 0) {
							this.empty = true
						} else {
							this.empty = false
						}
						uni.hideLoading();
						// console.log(this.addList.length);
						// if (this.news.length == 0) {
						// 	this.empty = true
						// } else {
						// 	this.empty = false
						// }
					},
					fail: () => {},
					complete: () => {}
				});
			},
			// 监听高度变化
			onHeight(height, tag) {
				if (tag == 'left') {
					this.leftHeight += height;
				} else {
					this.rightHeight += height;
				}
			},
			// 组件点击事件
			onClick(index, tag, e) {
				var topicId = e.currentTarget.dataset.currentid;
				var jumpId = e.currentTarget.dataset.jumpid;

				if (jumpId == 2) {
					uni.navigateTo({
						url: "/pages/about/about",
					})
				} else {
					uni.navigateTo({
						url: "/pages/article/article2?TopicId=" + topicId,
					})
				}
			},
			addList(res) {
				// 获取到的数据，请注意数据结构
				// console.log('addList_data_length',res.data.length);

				if (res.data.length < 1) {
					this.ajax.loadTxt = '没有更多了';
					return;
				}

				// 左右列表高度的差
				let differ = this.leftHeight - this.rightHeight;
				// 计算差值，用于确定优先插入那一边
				let differVal = 0;

				// 初始化左右列表的数据
				let i = differ > 0 ? 1 : 0;

				let [left, right] = [
					[],
					[]
				];

				// 获取插入的方向
				let getDirection = (index) => {
					/* 左侧高度大于右侧超过 600px 时，则前3条数据都插入到右边 */
					if (differ >= 600 && index < 3) {
						differVal = 1;
						return 'right';
					}

					/* 右侧高度大于左侧超过 600px 时，则前3条数据都插入到左边 */
					if (differ <= -600 && index < 3) {
						differVal = -1;
						return 'left';
					}

					/* 左侧高度大于右侧超过 350px 时，则前2条数据都插入到右边 */
					if (differ >= 350 && index < 2) {
						return 'right';
					}
					/* 右侧高度大于左侧超过 350px 时，则前2条数据都插入到左边 */
					if (differ <= -350 && index < 2) {
						differVal = -1;
						return 'left';
					}

					/* 当前数据序号为偶数时，则插入到左边 */
					if ((i + differVal) % 2 == 0) {
						return 'left';
					} else {
						/* 当前数据序号为奇数时，则插入到右边 */
						return 'right';
					}
				}

				// 将数据源分为左右两个列表，容错差值请自行根据项目中的数据情况调节
				res.data.forEach((item, index) => {
					if (getDirection(index) == 'left') {
						//console.log(`差值：${differ},方向：left，序号${index}`)
						left.push(item);
					} else {
						//console.log(`差值：${differ},方向：right，序号${index}`)
						right.push(item);
					}
					i++;
				});

				this.leftList = [...this.leftList, ...left];
				this.rightList = [...this.rightList, ...right];

				this.ajax.load = true;
				this.ajax.loadTxt = '加载中...';
				this.ajax.page++;
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}

	.home_header {
		background-color: #fff;
	}

	.meitu_ad {
		width: 25px;
		height: 25px;
		background: #FFD84A;
		text-align: center;
		font-size: 10px;
		padding: 5px;
		border-radius: 10px;
	}

	.home_tab {
		background: #fff;
		padding: 0 0 5px 0;
	}

	.waterfall-box {
		padding: 20rpx 10rpx;
		box-sizing: border-box;

		>view {
			padding: 0 10rpx;
		}
	}

	.h-flex-x {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;

		&.h-flex-2 {
			>view {
				width: 50%;
			}
		}
	}

	.load-txt {
		padding: 0 0 20rpx 0;
		text-align: center;
		color: #999;
		font-size: 24rpx;
	}

	.bottom_menu {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		bottom: constant(safe-area-inset-bottom);
		bottom: env(safe-area-inset-bottom);
		box-sizing: border-box;
	}

	.lbs_chioce {
		padding: 6px 12px;
	}

	.lbs_text text {
		margin: 0 6px;
		padding: 3px 6px;
	}

	.selected {
		background-color: #FFD84A;
		padding: 3px 6px;
		margin: 0 6px;
		border-radius: 25px;

	}

	// .index_menu {
	// 	margin-top: 70px;
	// }
	// .index_body {
	// 	margin-top: 115px;
	// }
</style>